﻿/**
*   A Very basic Model class
*/

function ViewNotifiableModel(){
    var _this=this;
    var _oView=null;
    
    this.setView=function(oView){_oView=oView;}
    
    this.notify=function(){
        _oView.update(_this);
    }
}

function Model(){
    ViewNotifiableModel.call(this);
    var _this=this;

    var _iValue1=0;
    var _iValue2=0;
    var _iResult=0;
    
    this.setValue1=function(iValue){_iValue1=iValue;calculateResult();}
    this.getValue1=function(){return _iValue1;}
    
    this.setValue2=function(iValue){_iValue2=iValue;calculateResult();}
    this.getValue2=function(){return _iValue2;}
    
    this.getResult=function(){return _iResult;}
    
    function calculateResult(){
        _iResult=parseFloat(_iValue1)+parseFloat(_iValue2);
        _this.notify();
    }
}


function ModelAwareView(oViewNotifiableModel){
    var _oViewNotifiableModel=oViewNotifiableModel || null;
    
    this.setModel=function(oModel){_oViewNotifiableModel=oModel;}
    this.getModel=function(){return _oViewNotifiableModel;}
}

function View(oModel){
    ModelAwareView.call(this);
    var _this=this;
    
    var _oField1=$('form fieldset input#iValue1')[0];
    var _oField2=$('form fieldset input#iValue2')[0];
    var _oField3=$('form fieldset input#iResult')[0];
    
    _this.onValue1Changed=function(){}
    _this.onValue2Changed=function(){}
    
    function onValue1Changed(){
        _this.onValue1Changed(_oField1.value);
    }
    
    function onValue2Changed(){
        _this.onValue2Changed(_oField2.value);
    }
    
    $(_oField1).bind('keyup',onValue1Changed);
    $(_oField2).bind('keyup',onValue2Changed);
    
    this.update=function(oModel){
        _oField1.value=oModel.getValue1();
        _oField2.value=oModel.getValue2();
        _oField3.value=oModel.getResult();
    }    
}

function Controller(oModel,oView){
    
    var _oModel=oModel;
    var _oView=oView;
    
    //  Invoked by container when context support is provided
    this.onContextSupport=function(oContainerContext){  
        _oView.update(_oModel);
        
        _oView.onValue1Changed=function(oValue){
            _oModel.setValue1(oValue);
            //alert("JKH");
        }
        
        _oView.onValue2Changed=function(oValue){
            _oModel.setValue2(oValue);
        }
    }
}